package pl.ericpol.kernel.logic;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import pl.ericpol.kernel.schemas.Schema;
import pl.ericpol.kernel.schemas.SchemaBuilder;
import pl.ericpol.stubs.LampAdapterStub;

public class Logic {
	
	private static Logger logger = LogManager.getLogger(Logic.class);
	
	private List<Schema> currentSchemas;
	//private SchemaBuilder schemaBuilder;
	
	
	public Logic(List<Schema> currentSchemas) {
		this.currentSchemas = currentSchemas;
		
	}
	
	public Logic() {
		currentSchemas = new ArrayList<Schema>();
	}

	public Schema createSchema(SchemaBuilder schemaBuilder, String filepath, String schemaName) {
		Schema newSchema = schemaBuilder.createSchema(filepath, schemaName);
		logger.info("Create schema with class: "+schemaBuilder.getClass()+" and filepath :"+filepath);
		return newSchema;
	}
	
	public void addSchema(SchemaBuilder schemaBuilder, String filepath, String schemaName) {
		currentSchemas.add(createSchema(schemaBuilder, filepath, schemaName));
		logger.info("add schema. currentSchemas size is "+currentSchemas.size());
	}
	
	public void replaceSchema(String oldSchemaName, SchemaBuilder schemaBuilder, String filepath, String newSchemaName) {
		Schema newSchema = createSchema(schemaBuilder, filepath, newSchemaName);
		int numberSchema = findSchemaByName(oldSchemaName);
		currentSchemas.set(numberSchema, newSchema);
		logger.info("replace schema");
	}
	
	/**
	 * Find schema by name. Return number of schema or -1 if schema was not found.
	 * 
	 * @param name
	 * @return
	 */
	public int findSchemaByName(String name) {
		int result = -1;
		for (int i=0; i<currentSchemas.size(); i++) {
			if (currentSchemas.get(i).getName().equals(name)) {
				result=i;
				break;
			}
		}
		return result;
	}
	
	public void run() {
		for (Schema schema: currentSchemas) {
			new Thread(new SchemaExecute(schema)).start();
			logger.info("Run new schema with name: "+schema.getName());
		}		
	}
	

}
